import 'package:flutter/material.dart';
import '../../models/user_model.dart';
import '../../models/follow_category_model.dart';
import '../../models/talent_user_model.dart';
import '../../widgets/skill_tag_widget.dart';
import '../../services/talent_service.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import '../hot/hot_page.dart';
import '../profile/profile_page.dart';
import '../user/user_detail_page.dart';
import '../chat/chat_list_page.dart';
import '../chat/chat_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key, this.initialIndex = 0});

  final int initialIndex;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late int _currentIndex;
  String _selectedCategory = '全部';
  final TextEditingController _searchController = TextEditingController();

  // 人才服务
  final TalentService _talentService = TalentService();
  final ApiService _apiService = ApiService();

  // 人才列表数据
  List<TalentUserModel> _talentUsers = [];
  bool _isLoadingTalents = false;
  bool _hasLoadedTalents = false;
  String? _currentUserId;

  // 技能分类列表
  List<String> _skillCategories = [
    '全部',
    '编程',
    '设计',
    '营销',
    '运营',
    '教育',
    '医疗',
    '法律',
    '金融',
    '其他'
  ];

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _initData();
  }

  /// 初始化数据
  Future<void> _initData() async {
    _currentUserId = await _apiService.getUserId();
    // _loadSkillCategories(); // 后端接口未实现，暂时使用默认分类
  }

  /// 加载技能分类（暂未使用，等待后端接口实现）
  Future<void> _loadSkillCategories() async {
    try {
      final categories = await _talentService.getSkillCategories();
      if (mounted && categories.isNotEmpty) {
        setState(() {
          _skillCategories = categories;
        });
      }
    } catch (e) {
      Logger.w('HOME_PAGE', '加载技能分类失败: $e');
    }
  }

  /// 加载人才列表
  Future<void> _loadTalentUsers() async {
    if (_isLoadingTalents) return;

    setState(() {
      _isLoadingTalents = true;
    });

    try {
      final userId = int.tryParse(_currentUserId ?? '0') ?? 0;
      final users = await _talentService.getDiscoverUsers(
        userId: userId,
        limit: 30,
      );

      if (mounted) {
        setState(() {
          _talentUsers = users;
          _isLoadingTalents = false;
          _hasLoadedTalents = true;
        });
      }
    } catch (e) {
      Logger.e('HOME_PAGE', '加载人才列表失败: $e');
      if (mounted) {
        setState(() {
          _isLoadingTalents = false;
          _hasLoadedTalents = true;
        });
      }
    }
  }

  /// 搜索人才
  Future<void> _searchTalents(String keyword) async {
    if (keyword.isEmpty) {
      _loadTalentUsers();
      return;
    }

    setState(() {
      _isLoadingTalents = true;
    });

    try {
      final users = await _talentService.searchUsers(
        keyword: keyword,
        category: _selectedCategory != '全部' ? _selectedCategory : null,
      );

      if (mounted) {
        setState(() {
          _talentUsers = users;
          _isLoadingTalents = false;
        });
      }
    } catch (e) {
      Logger.e('HOME_PAGE', '搜索人才失败: $e');
      if (mounted) {
        setState(() {
          _isLoadingTalents = false;
        });
      }
    }
  }

  /// 按分类筛选
  Future<void> _filterByCategory(String category) async {
    setState(() {
      _selectedCategory = category;
      _isLoadingTalents = true;
    });

    try {
      List<TalentUserModel> users;

      if (_searchController.text.isNotEmpty) {
        users = await _talentService.searchUsers(
          keyword: _searchController.text,
          category: category != '全部' ? category : null,
        );
      } else {
        users = await _talentService.getDiscoverUsers(
          userId: int.tryParse(_currentUserId ?? '0') ?? 0,
          limit: 30,
        );

        // 本地筛选分类
        if (category != '全部') {
          users = users
              .where((u) => u.tags.any((tag) => tag.contains(category)))
              .toList();
        }
      }

      if (mounted) {
        setState(() {
          _talentUsers = users;
          _isLoadingTalents = false;
        });
      }
    } catch (e) {
      Logger.e('HOME_PAGE', '筛选人才失败: $e');
      if (mounted) {
        setState(() {
          _isLoadingTalents = false;
        });
      }
    }
  }

  // 未读消息数量
  int _unreadUserMessages = 0;

  // 广告数据
  final Map<String, dynamic> _adData = {
    'title': '限时优惠：专业认证服务',
    'subtitle': '提升您的专业可信度，获得更多客户信任',
    'image': '',
    'actionText': '立即认证',
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _currentIndex,
        children: [
          const HotPage(),
          _buildTalentDiscoveryPage(),
          _buildChatPage(),
          const ProfilePage(),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.whatshot),
            label: '热门',
          ),
          BottomNavigationBarItem(
            icon: Stack(
              children: [
                const Icon(Icons.search),
                if (_unreadUserMessages > 0)
                  Positioned(
                    right: 0,
                    top: 0,
                    child: Container(
                      padding: const EdgeInsets.all(2),
                      decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      constraints: const BoxConstraints(
                        minWidth: 16,
                        minHeight: 16,
                      ),
                      child: Text(
                        _unreadUserMessages > 99
                            ? '99+'
                            : _unreadUserMessages.toString(),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
              ],
            ),
            label: '人才',
          ),
          const BottomNavigationBarItem(
            icon: Icon(Icons.chat),
            label: '聊天',
          ),
          const BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: '我的',
          ),
        ],
      ),
    );
  }

  Widget _buildTalentDiscoveryPage() {
    // 首次加载时获取数据
    if (!_hasLoadedTalents && !_isLoadingTalents) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _loadTalentUsers();
      });
    }

    return Column(
      children: [
        // 广告位
        _buildAdBanner(),

        // 搜索栏
        Container(
          padding: const EdgeInsets.all(16.0),
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withValues(alpha: 0.1),
                spreadRadius: 1,
                blurRadius: 3,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Column(
            children: [
              // 搜索框
              TextField(
                controller: _searchController,
                decoration: InputDecoration(
                  hintText: '搜索技能、人才...',
                  prefixIcon: const Icon(Icons.search),
                  suffixIcon: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (_searchController.text.isNotEmpty)
                        IconButton(
                          icon: const Icon(Icons.clear),
                          onPressed: () {
                            _searchController.clear();
                            _loadTalentUsers();
                          },
                        ),
                      IconButton(
                        icon: const Icon(Icons.filter_list),
                        onPressed: _showFilterDialog,
                      ),
                    ],
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25),
                    borderSide: BorderSide.none,
                  ),
                  filled: true,
                  fillColor: Colors.grey[100],
                ),
                onSubmitted: (value) => _searchTalents(value),
              ),
              const SizedBox(height: 12),
              // 分类筛选标签
              SizedBox(
                height: 36,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: _skillCategories.length,
                  itemBuilder: (context, index) {
                    final category = _skillCategories[index];
                    final isSelected = _selectedCategory == category;
                    return Padding(
                      padding: const EdgeInsets.only(right: 8),
                      child: ChoiceChip(
                        label: Text(category),
                        selected: isSelected,
                        onSelected: (selected) {
                          if (selected) {
                            _filterByCategory(category);
                          }
                        },
                        selectedColor: Theme.of(context)
                            .primaryColor
                            .withValues(alpha: 0.2),
                        labelStyle: TextStyle(
                          color: isSelected
                              ? Theme.of(context).primaryColor
                              : Colors.grey[700],
                          fontSize: 13,
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),

        // 人才列表
        Expanded(
          child: _isLoadingTalents
              ? const Center(child: CircularProgressIndicator())
              : _talentUsers.isEmpty
                  ? _buildEmptyState()
                  : RefreshIndicator(
                      onRefresh: _loadTalentUsers,
                      child: ListView.builder(
                        padding: const EdgeInsets.all(16.0),
                        itemCount: _talentUsers.length,
                        itemBuilder: (context, index) {
                          final user = _talentUsers[index];
                          return _buildTalentUserCard(user);
                        },
                      ),
                    ),
        ),
      ],
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.person_search,
            size: 80,
            color: Colors.grey[300],
          ),
          const SizedBox(height: 16),
          Text(
            '暂无相关人才',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '换个关键词试试',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[400],
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: _loadTalentUsers,
            child: const Text('刷新'),
          ),
        ],
      ),
    );
  }

  /// 构建人才用户卡片（使用TalentUserModel）
  Widget _buildTalentUserCard(TalentUserModel user) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: InkWell(
        onTap: () => _navigateToUserDetail(user),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户头部信息
              Row(
                children: [
                  // 头像
                  Stack(
                    children: [
                      CachedAvatarWidget(
                        avatarUrl: user.avatar,
                        size: 56,
                      ),
                      // 在线状态
                      if (user.isOnline)
                        Positioned(
                          right: 0,
                          bottom: 0,
                          child: Container(
                            width: 14,
                            height: 14,
                            decoration: BoxDecoration(
                              color: Colors.green,
                              shape: BoxShape.circle,
                              border: Border.all(color: Colors.white, width: 2),
                            ),
                          ),
                        ),
                    ],
                  ),
                  const SizedBox(width: 12),
                  // 用户信息
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Flexible(
                              child: Text(
                                user.nickname,
                                style: const TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            if (user.isHot) ...[
                              const SizedBox(width: 6),
                              Container(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 6,
                                  vertical: 2,
                                ),
                                decoration: BoxDecoration(
                                  color: Colors.red[50],
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Icon(Icons.whatshot,
                                        size: 12, color: Colors.red[400]),
                                    const SizedBox(width: 2),
                                    Text(
                                      '热门',
                                      style: TextStyle(
                                        fontSize: 10,
                                        color: Colors.red[400],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ],
                        ),
                        const SizedBox(height: 2),
                        // 用户ID
                        Text(
                          'ID: ${user.id}',
                          style: TextStyle(
                            fontSize: 11,
                            color: Colors.grey[500],
                            fontFamily: 'monospace',
                          ),
                        ),
                        const SizedBox(height: 4),
                        // 位置和距离
                        Row(
                          children: [
                            if (user.location != null &&
                                user.location!.isNotEmpty) ...[
                              Icon(Icons.location_on,
                                  size: 14, color: Colors.grey[500]),
                              const SizedBox(width: 2),
                              Flexible(
                                child: Text(
                                  user.location!,
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Colors.grey[600],
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                            if (user.distance != null) ...[
                              const SizedBox(width: 8),
                              Text(
                                user.formattedDistance,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey[500],
                                ),
                              ),
                            ],
                          ],
                        ),
                      ],
                    ),
                  ),
                  // 评分
                  if (user.rating != null)
                    Column(
                      children: [
                        Row(
                          children: [
                            const Icon(Icons.star,
                                size: 16, color: Colors.amber),
                            const SizedBox(width: 2),
                            Text(
                              user.formattedRating,
                              style: const TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                        if (user.reviewCount != null)
                          Text(
                            '${user.reviewCount}条评价',
                            style: TextStyle(
                              fontSize: 10,
                              color: Colors.grey[500],
                            ),
                          ),
                      ],
                    ),
                ],
              ),

              // 简介
              if (user.bio != null && user.bio!.isNotEmpty) ...[
                const SizedBox(height: 12),
                Text(
                  user.bio!,
                  style: TextStyle(
                    fontSize: 13,
                    color: Colors.grey[700],
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],

              // 技能标签
              if (user.tags.isNotEmpty) ...[
                const SizedBox(height: 12),
                Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  children: user.tags.take(5).map((tag) {
                    return Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: Theme.of(context)
                            .primaryColor
                            .withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        tag,
                        style: TextStyle(
                          fontSize: 12,
                          color: Theme.of(context).primaryColor,
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ],

              // 底部信息
              const SizedBox(height: 12),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // 粉丝数
                  if (user.followersCount != null)
                    Text(
                      '${user.followersCount}粉丝',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[500],
                      ),
                    ),
                  // 操作按钮
                  Row(
                    children: [
                      OutlinedButton(
                        onPressed: () => _navigateToChat(user),
                        style: OutlinedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 6,
                          ),
                          minimumSize: Size.zero,
                        ),
                        child: const Text('私信', style: TextStyle(fontSize: 12)),
                      ),
                      const SizedBox(width: 8),
                      ElevatedButton(
                        onPressed: () => _navigateToUserDetail(user),
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 6,
                          ),
                          minimumSize: Size.zero,
                        ),
                        child: const Text('查看', style: TextStyle(fontSize: 12)),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 跳转到用户详情页
  void _navigateToUserDetail(TalentUserModel talentUser) {
    // 将TalentUserModel转换为UserModel
    final user = UserModel(
      id: talentUser.id.toString(),
      username: talentUser.nickname,
      email: '',
      avatar: talentUser.avatar ?? '',
      bio: talentUser.bio ?? '',
      location: talentUser.location ?? '',
      skills: talentUser.tags
          .map((tag) => SkillTag(
                id: tag,
                name: tag,
                category: '技能',
                level: SkillLevel.intermediate,
                isCertified: false,
                createdAt: DateTime.now(),
              ))
          .toList(),
      rating: talentUser.rating ?? 0,
      reviewCount: talentUser.reviewCount ?? 0,
      followersCount: talentUser.followersCount ?? 0,
      followingCount: 0,
      isOnline: talentUser.isOnline,
      createdAt: DateTime.now(),
    );

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => UserDetailPage(user: user),
      ),
    );
  }

  /// 跳转到聊天页
  void _navigateToChat(TalentUserModel talentUser) {
    // 将TalentUserModel转换为UserModel
    final user = UserModel(
      id: talentUser.id.toString(),
      username: talentUser.nickname,
      email: '',
      avatar: talentUser.avatar ?? '',
      bio: talentUser.bio ?? '',
      location: talentUser.location ?? '',
      skills: [],
      rating: talentUser.rating ?? 0,
      reviewCount: talentUser.reviewCount ?? 0,
      followersCount: talentUser.followersCount ?? 0,
      followingCount: 0,
      isOnline: talentUser.isOnline,
      createdAt: DateTime.now(),
    );

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChatPage(targetUser: user),
      ),
    );
  }

  Widget _buildAdBanner() {
    return Container(
      margin: const EdgeInsets.all(16),
      height: 120,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Theme.of(context).primaryColor,
            Theme.of(context).primaryColor.withOpacity(0.8),
          ],
        ),
      ),
      child: Stack(
        children: [
          // 背景图片
          Positioned.fill(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: Image.network(
                _adData['image'],
                fit: BoxFit.cover,
              ),
            ),
          ),
          // 渐变遮罩
          Positioned.fill(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12),
                gradient: LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Colors.black.withOpacity(0.6),
                    Colors.transparent,
                  ],
                ),
              ),
            ),
          ),
          // 内容
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  _adData['title'],
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  _adData['subtitle'],
                  style: TextStyle(
                    color: Colors.white.withOpacity(0.9),
                    fontSize: 14,
                  ),
                ),
                const SizedBox(height: 12),
                ElevatedButton(
                  onPressed: () => _showAdAction(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    foregroundColor: Theme.of(context).primaryColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: Text(_adData['actionText']),
                ),
              ],
            ),
          ),
          // 关闭按钮
          Positioned(
            top: 8,
            right: 8,
            child: IconButton(
              icon: const Icon(Icons.close, color: Colors.white),
              onPressed: () {
                setState(() {
                  // 隐藏广告
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  void _showFilterDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('筛选条件'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('更多筛选功能开发中...'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showAdAction() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('专业认证'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('立即申请专业认证，提升您的可信度！'),
            SizedBox(height: 16),
            Text('认证优势：'),
            Text('• 获得认证标识'),
            Text('• 提升搜索排名'),
            Text('• 增加客户信任'),
            Text('• 优先推荐展示'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('认证功能开发中...')),
              );
            },
            child: const Text('立即认证'),
          ),
        ],
      ),
    );
  }

  // 构建聊天页面
  Widget _buildChatPage() {
    return const ChatListPage();
  }
}
